const jwt = require('jsonwebtoken');
// const basicAuth = require("basic-auth")
module.exports = {
    async auth(ctx,next){
        //判断是否处于登录状态
        try {
            // const token = basicAuth(ctx.request).name;
            const token = ctx.cookies.get("Admin-Token")
            //{id,name,roles}
            const loginUser = await jwt.verify(token,process.env.jwtstep);
            ctx.loginUser = loginUser;
            await next()
        } catch (error) {
            ctx.body= {
                code: 50008,
                message: 'Login failed, unable to get user details.'
            }
            throw new Error(error)
        }
    },
    async check(ctx,next){
        //判断登录的用户 和 需要头像的用户是否是同一个
        const loginUserId = ctx.loginUser.id ;
        const avatarId = ctx.params.userid;
        if(loginUserId !== avatarId){
            ctx.status = 412;
            ctx.body = "跟谁两呢 给谁整头像呢"
            ctx.throw(412,"跟谁两呢 给谁整头像呢");
        }
        await next()
    }
}